package com.power.wx.servlet;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.power.wx.bean.Message;
import com.power.wx.bean.TextDecision;
import com.qq.weixin.WxConfig;
import com.qq.weixin.mp.aes.AesException;
import com.qq.weixin.mp.aes.WXBizMsgCrypt;
import com.qq.weixin.util.StreamUtils;
import com.qq.weixin.util.XMLConverUtil;

public class WechatServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = -6221781550363875917L;

	private static final Logger logger = Logger.getLogger(WechatServlet.class);

	private WxConfig wxConfig;

	@Override
	public void init() throws ServletException {
		super.init();
		ServletContext servletContext = getServletContext();
		WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
		wxConfig = (WxConfig) applicationContext.getBean("wxConfig");
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		logger.info("in get............");
		String signature = req.getParameter("signature");
		logger.info(signature);
		logger.info("appid" + wxConfig.getAppId());
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		logger.info("in post............");
		String signature = req.getParameter("signature");
		String timestamp = req.getParameter("timestamp");
		String nonce = req.getParameter("nonce");
		String encrypt_type = req.getParameter("encrypt_type");
		String msg_signature = req.getParameter("msg_signature");

		ServletInputStream inputStream = req.getInputStream();
		String xml = StreamUtils.copyToString(inputStream, Charset.forName("utf-8"));
		logger.info("xml=" + xml);

		Message message = XMLConverUtil.convertToObject(Message.class, xml);

		resp.setContentType("text/xml;charset=UTF-8");
		ServletOutputStream outputStream = resp.getOutputStream();
		if ("hello".equals(message.getContent())) {
			TextDecision textDecision = new TextDecision(message.getFromUserName(), message.getToUserName(), (int) (System.currentTimeMillis() / 1000),
					"Hello Wechat");
			WXBizMsgCrypt pc = null;
			try {
				pc = new WXBizMsgCrypt(wxConfig.getToken(), wxConfig.getEncodingAesKey(), wxConfig.getAppId());
			} catch (AesException e) {
				logger.error(e, e);
				emptyResponse(outputStream);
				return;
			}
			boolean success = textDecision.outputStreamWrite(outputStream, pc);
			if (success)
				return;
		}

		// TODO default response
		emptyResponse(outputStream);
	}

	private void emptyResponse(OutputStream outputStream) {
		logger.info("empty");
		outputStreamWrite(outputStream, "");
	}

	private boolean outputStreamWrite(OutputStream outputStream, String text) {
		try {
			outputStream.write(text.getBytes("utf-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	public static void main(String[] args) {
		String xml = "<xml><URL><![CDATA[http://wx.200power.com]]></URL><ToUserName><![CDATA[97521799]]></ToUserName><FromUserName><![CDATA[97521798]]></FromUserName><CreateTime>1237872781</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[HellowWechat]]></Content><MsgId>11111</MsgId><Encrypt><![CDATA[vtCLYY9n/OEM/RfSDSRtGSseSa5NshpKRT9TgoSkngIFz9Hff+5ENF+8mTrL2QGow/VUuwnwr3yg1heKz8edm6ZZhnUL+cRH41Et0HmXl3uTUNJSoeQEcQcpXKuqwWwZ0sf0o8nAm3OTthvGre21jXLTf8iluStL7qp4CrAPv6rFfYHDpt98HhKHX3FkLOMJzhmEfs2RqZmnQtftd+bA6TKeVW9bQT+4uV4LlYwOFGxlnHCiyEEYmw0WuIxcKbWXD7ZX6Owhcmm2JrYUQYJRYvfNB1LMN8vJ8HaVgmnhl5v/Nlw6qoflmG6CU1PXYwpGxqP3LWjj1qvnCcYOw8b877jnUcEZFz6x0fkWy/5tjM3wOKw3bTE4oOjsTFVS9h2GJZKkenbB4izzywv27upJo44ER05ZtHIpaEiKmdUpOydG0KpIbi2zfId4RdaffY+9AbWW8XvQGuhBtma9MTbtRA==]]></Encrypt></xml>";
		Message obj = XMLConverUtil.convertToObject(Message.class, xml);
		logger.info(obj);
	}
}
